package com.peter.springcloud.streamclient.rest;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.shared.Applications;
import com.peter.springcloud.streamclient.client.RabbitClient;

@RestController
public class DcController {
    private Logger logger = LogManager.getLogger(getClass());

    @Autowired
    private EurekaClient discoveryClient;
    // private DiscoveryClient discoveryClient;
    @Autowired
    private RabbitClient client;

    @GetMapping("/dc")
    public Applications dc() {
        return discoveryClient.getApplications();
    }

    @GetMapping("/publish")
    public String publish() {
        int sum = 9000;

        for(int i = 0; i < sum; i++) {
            client.output().send(MessageBuilder.withPayload("peter_" + i).build());
        }

        return sum + "";
    }

    @GetMapping("/get")
    public String get() {
        // 相当于增加一个监听对象。
        client.input().subscribe(new MessageHandler() {
            @Override
            public void handleMessage(Message<?> message) throws MessagingException {
                logger.info(">>> by controller: " + message.getPayload().getClass() + ", " + message);
            }
        });

        return "OK";
    }
}
